import { useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import type { Socket } from 'socket.io-client';
import { io } from 'socket.io-client';
import { useAppDispatch, useAppSelector } from '../../redux/hooks';
import { setGame } from '../../redux/slices/gameSlice';
import { setFalseAnswer, setUserId, sethasAnswer } from '../../redux/slices/userSlice';

import { setId, setWsStatus } from '../../redux/slices/wsSlice';
import { startTimer, resetTimer } from '../../redux/timer/timerSlice';
import type { GameType } from '../../types/socketType';

export default function useSocket(): {
  createRoomHandler: (arg: number) => void;
  startHandler: (roomName: string | null) => void;
  answerHandler: (id: number) => void;
} {
  const socketRef = useRef<null | Socket>(null);
  const dispatch = useAppDispatch();
  const navigate = useNavigate();
  const userId = useAppSelector((state) => state.ws.id);
  const user = useAppSelector((state) => state.user);
  const room = useAppSelector((state) => state.game.roomName);

  useEffect(() => {
    if (user.name) {
      socketRef.current = io('/'); // /wsapp ???

      const socket = socketRef.current;

      socket.on('connect', () => {
        dispatch(setWsStatus(true));
      });

      socket.on('connect_error', () => {
        dispatch(setWsStatus(false));
      });

      socket.on('my_name', (data: string) => {
        console.log('myname---', data);
        dispatch(setId(data));
        dispatch(setUserId(data));
      });

      socket.on('start', (data: GameType) => {
        dispatch(setGame(data));
        dispatch(startTimer());
        navigate('/game');
      });

      socket.on('nextquestion', (data: GameType) => {
        dispatch(setGame(data));
        dispatch(setFalseAnswer());
        dispatch(resetTimer());
      });

      socketRef.current.on('newScore', (data: GameType) => {
        dispatch(setGame(data));
      });

      socketRef.current.on('results', (data: GameType) => {
        dispatch(setGame(data));
        navigate('/result');
      });
    }
  }, [user.name]);

  const createRoomHandler = (themeId: number): void => {
    const roomId = `${userId}${themeId}`;
    if (!socketRef.current) return;

    socketRef.current.emit('create_room', { user, themeId, roomId });
    socketRef.current.on('room_users', (data: GameType) => {
      dispatch(setGame(data));
    });
    navigate(`/linkpage/${roomId}`);
  };

  const startHandler = (roomName: string | null): void => {
    if (!socketRef.current) return;

    socketRef.current.emit('redirect', { roomName });
  };

  const answerHandler = (id: number): void => {
    dispatch(sethasAnswer());
    if (!socketRef.current) return;

    socketRef.current.emit('answer', { id, userId, room });
  };

  return { createRoomHandler, startHandler, answerHandler };
}
